﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using System.Web.Security;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;

namespace MVCTask.Controllers
{
    public class AuthenticationController : Controller
    {
        private static OpenIdRelyingParty openid = new OpenIdRelyingParty();

        /// <summary>
        /// Authentication/Login post action.
        /// Original code concept from
        /// DotNetOpenAuth/Samples/OpenIdRelyingPartyMvc/Controller/UserController
        /// </summary>
        [ValidateInput(false)]
        public ActionResult Authenticate()
        {
            bool remember_me = false;

            var response = openid.GetResponse();
            var statusMessage = "";
            //Check for the "remember" tag
            if (Request.Form["remember"] != null && Request.Form["remember"] == "on")
            {
                remember_me = true;
            }
            if (response == null)
            {
                Identifier id;
                //make sure your users openid_identifier is valid.
                if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
                {
                    try
                    {
                        //request openid_identifier
                        var req = openid.CreateRequest(Request.Form["openid_identifier"]);
                        var fields = new ClaimsRequest();
                        fields.Email = DemandLevel.Require;
                        fields.Nickname = DemandLevel.Require;
                        req.AddExtension(fields);
                        return req.RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException ex)
                    {
                        statusMessage = ex.Message;
                        ViewBag.message = statusMessage;
                        return View("Login");
                    }
                }
                else
                {
                    statusMessage = "Invalid identifier";
                    ViewBag.message = statusMessage;
                    return View("Login");
                }
            }
            else
            {
                //check the response status
                switch (response.Status)
                {
                    //success status
                    case AuthenticationStatus.Authenticated:
                        Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;

                        //TODO: response.ClaimedIdentifier, to login or create new account 
                        var claim = response.GetExtension<ClaimsResponse>();
                        string email = null;
                        if (claim != null)
                        {
                            email = claim.Email;
                        }
                        FormsAuthentication.SetAuthCookie(email, remember_me);
                        return RedirectToAction("Index", "Task");

                    case AuthenticationStatus.Canceled:
                        statusMessage = "Canceled at provider";
                        ViewBag.message = statusMessage;
                        return View("Login");

                    case AuthenticationStatus.Failed:
                        statusMessage = response.Exception.Message;
                        ViewBag.message = statusMessage;
                        return View("Login");
                }
            }
            return new EmptyResult();
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

            //redirect to logout success page in page /Authentication/Logout
            return View();
        }
    }
}
